package com.tanhua.app.controllerservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.UserHolder;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.template.OssTemplate;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTempalte;


    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    //小视频的查询 （mongodb-->redis）
    @Cacheable(value = "video")  //要求：返回值必须实现序列化
    public PageBeanVo smallVideos(Integer page, Integer pagesize) {

        System.out.println("我执行了...");

        //分页查询小视频
        PageBeanVo pageBeanvo=videoApi.findVideo(page,pagesize);
        List<Video> items = (List<Video>) pageBeanvo.getItems();

        List<VideoVo> voList=new ArrayList();
        if(CollectionUtil.isNotEmpty(items)){
            for (Video video : items) {
                // 查询用户数据
                UserInfo userInfo = userInfoApi.findUserInfo(video.getUserId());
                //封装vo返回
                VideoVo vo = new VideoVo();
                BeanUtil.copyProperties(userInfo,vo);
                vo.setUserId(userInfo.getId());
                BeanUtil.copyProperties(video,vo);
                vo.setCover(video.getPicUrl()); //封面
                vo.setSignature(video.getText());
                //是否高亮
                vo.setHasLiked(0);
                if(stringRedisTemplate.hasKey(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), video.getUserId()))){
                    vo.setHasFocus(1); //已关注
                }else{
                    vo.setHasFocus(0); //未关注
                }

                vo.setId(video.getId().toString());
                voList.add(vo);
            }
        }

        pageBeanvo.setItems(voList);

        return pageBeanvo;
    }


    // 小视频的新增 (redis--删除)
    @CacheEvict(value = "video",allEntries = true)
    public ResponseEntity toSmallVideos(MultipartFile fm, MultipartFile video) throws IOException {

        // 上传封面到oss
        String fm_url = ossTempalte.upload(fm.getOriginalFilename(), fm.getInputStream());
        // 上传小视频到fastDFS
        StorePath storePath = client.uploadFile(video.getInputStream(), video.getSize(), FileUtil.extName(video.getOriginalFilename()), null);
        String video_url =webServer.getWebServerUrl()+storePath.getFullPath();
        // 记录oss和fastDFS的地址 设置video属性 进行保存
        Video vd = new Video();
        vd.setPicUrl(fm_url);
        vd.setVideoUrl(video_url);
        vd.setUserId(UserHolder.getUser().getId());
        vd.setText("震惊,一男子夜里裸奔~");
        videoApi.save(vd);

        return ResponseEntity.ok(null);
    }







    public ResponseEntity userFocus(Integer vid) {

        FollowUser followUser = new FollowUser();
        followUser.setCreated(System.currentTimeMillis());
        followUser.setUserId(UserHolder.getUser().getId());
        followUser.setFollowUserId(vid.longValue());
        videoApi.saveFollowUser(followUser);

        stringRedisTemplate.opsForValue().set(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), vid), "1");

        return ResponseEntity.ok(null);
    }

    public ResponseEntity userUnFocus(Integer vid) {

        //根据关注人和被关注人的id做删除
        videoApi.delete(UserHolder.getUser().getId(),vid);
        // 删除redis中的关注标识
        stringRedisTemplate.delete(StrUtil.format("follow_user_{}_{}", UserHolder.getUser().getId(), vid));

        return ResponseEntity.ok(null);

    }
}
